package com.robot.admin.controller;

import com.alibaba.fastjson.JSON;
import com.robot.admin.client.OrdersClient;
import com.robot.admin.pojo.client.Confirmation;
import com.robot.admin.pojo.client.Purchase;
import com.robot.admin.service.AdminService;
import com.robot.admin.util.SendMessageUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 采购付款凭证模块
 *
 * @@author lin
 */
@RestController
@CrossOrigin
@RequestMapping("/confirmation")
public class ConfirmationController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private OrdersClient ordersClient;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SendMessageUtil sendMessageUtil;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 条件搜索采购付款凭证
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "{page}/{size}", method = RequestMethod.POST)
    public Result findConfirmations(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        return new Result(StatusCode.SUCCESS_QUERY, JSON.parseObject(ordersClient.thirdFindConfirmationsBySearch(searchMap, page, size)));
    }

    /**
     * 根据ID查询采购付款凭证
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    public Result findConfirmation(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Confirmation confirmationInDb = JSON.parseObject(ordersClient.thirdFindConfirmationById(id), Confirmation.class);
        logger.info("confirmationInDb=" + confirmationInDb);
        String message = checkPojo(confirmationInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS, confirmationInDb);
    }

    /**
     * 审核采购付款凭证
     *
     * @param confirmation
     * @param id
     * @return
     */
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    public Result updateConfirmation(@RequestBody Confirmation confirmation, @PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_admin");
        //判断是否登录
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        String status = confirmation.getStatus();
        logger.info("status=" + status);
        if (status == null || "".equals(status)) {
            return new Result(StatusCode.ERROR_STATUS_REQUIRED);
        }
        /**
         * confirmation表status状态0-待确认 1-已确认 2-驳回
         */
        String confirmationStatus = "0";
        String confirmationStatusFailed = "2";
        String confirmationStatusSuccess = "1";
        if (!(confirmationStatus.equals(status) || confirmationStatusSuccess.equals(status) || confirmationStatusFailed.equals(status))) {
            return new Result(StatusCode.ERROR_STATUS_INVALID);
        }

        Confirmation confirmationInDb = JSON.parseObject(ordersClient.thirdFindConfirmationById(id), Confirmation.class);
        logger.info("confirmationInDb=" + confirmationInDb);
        String message = checkPojo(confirmationInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }
        if (confirmationStatusSuccess.equals(confirmationInDb.getStatus())) {
            return new Result(StatusCode.FAIL, "申请单状态是已通过,不能修改");
        }
        if (confirmationStatusSuccess.equals(status)) {
            confirmationInDb.setStatus(status);
            //通过则新建采购单

            ordersClient.thirdAddPurchase(JSON.toJSONString(addPurchase(confirmationInDb)));
        }
        if (confirmationStatusFailed.equals(status)) {
            String remark = confirmation.getRemark();
            if (remark == null || "".equals(remark)) {
                return new Result(StatusCode.ERROR, "驳回原因必填");
            }
            confirmationInDb.setRemark(remark);
            confirmationInDb.setStatus(status);
        }

        ordersClient.thirdUpdateConfirmation(JSON.toJSONString(confirmationInDb));
        return new Result(StatusCode.SUCCESS_UPDATED);
    }


    /**
     * 消息推送
     *
     * @param map
     * @return
     */
    @PostMapping("messagePush")
    public Result sendSms(@RequestBody Map map) {
        Map<String, Object> resultMap = sendMessageUtil.sendMessage(map);
        return new Result(StatusCode.SUCCESS_SEND);
    }

    /**
     * 检查实体类是否存在
     *
     * @param confirmationInDb
     * @return
     */
    public String checkPojo(Confirmation confirmationInDb) {
        if (confirmationInDb == null) {
            return ("该采购付款凭证不存在");
        }
        if (confirmationInDb.getDeletedAt() != null) {
            return ("该采购付款凭证已被删除");
        }
        return "";
    }

    /**
     * 通过则新建采购单
     *
     * @param confirmationInDb
     * @return
     */
    public Purchase addPurchase(Confirmation confirmationInDb) {
        Purchase purchase = new Purchase();
        purchase.setCompanyId(confirmationInDb.getCompanyId());
        purchase.setStoreId(confirmationInDb.getStoreId());
        purchase.setStoreName(confirmationInDb.getStoreName());
        purchase.setAgentId(confirmationInDb.getAgentId());
        purchase.setAgentName(confirmationInDb.getAgentName());
        purchase.setAgentPhone(confirmationInDb.getAgentPhone());
        purchase.setArea(confirmationInDb.getArea());
        purchase.setFacePrice(confirmationInDb.getFacePrice());
        purchase.setSellingPrice(confirmationInDb.getSellingPrice());
        purchase.setRate(confirmationInDb.getRate());
        purchase.setBalance(confirmationInDb.getFacePrice());
        return purchase;
    }
}
